from machine import I2C,Pin
import network,time,usocket
from ssd1306 import SSD1306_I2C #从 ssd1306 模块中导入 SSD1306_I2C 子模块

i2c = I2C(sda=Pin(45), scl=Pin(46))
#OLED 显示屏初始化：128*64 分辨率, I2C 地址是 0x3c
oled = SSD1306_I2C(128, 64, i2c, addr=0x3c)

led_gpio = 48
p38= Pin(led_gpio,Pin.OUT)

wlan=network.WLAN(network.STA_IF)
skt = usocket.socket()

p2= Pin(2,Pin.OUT)

def oledShow(message):
    oled.fill(0)
    oled.show()
    oled.text(message[0], 0, 0) #写入第 1 行内容
    oled.text(message[1], 0, 10,1) #写入第 1 行内容
    oled.text(message[2], 0, 20,1) #写入第 1 行内容
    oled.text(message[3], 0, 30,1) #写入第 1 行内容
    oled.show() #OLED 执行显示

def oledMessage(message):
    oled.fill(0)
    oled.show()
    oled.text(message, 0, 0) #写入第 1 行内容
    oled.show() #OLED 执行显
    

def wifiConnect():
    wlan.active(True)
    startTime=time.time()
    if not wlan.isconnected():
        wlan.connect(ssid,password)
        print("正在连接网络")
        while not wlan.isconnected():
            print(".")
            p38.value(0)
            time.sleep_ms(200)
            p38.value(1)
            time.sleep_ms(200)
            if time.time()-startTime>10:
                print("连接网络超时失败，请重试@")
                p38.value(1)
                break
            
    

if __name__=="__main__":
    # connect wifi
    wlan.active(True)
    nwifi=wlan.scan()
    print("可用网络",nwifi)
    ssid = "Lanmei"
    password="Lanmei666"
    wifiConnect()
    
    if wlan.isconnected():
        print("---------")
        print("连接到网络：",ssid)
        print("网络配置信息")
        print(wlan.ifconfig())
        # show oled wifi
        oledShow(wlan.ifconfig())
        
    else:
        pass
        
    
    ip = "192.168.1.4"
    port =10000
    
    if wlan.isconnected():
        # 连接tcp
        skt.connect((ip,port))
        skt.send("hello ")
        while True:
            temp = skt.recv(128)
            print("receive data :",temp)
            oledMessage(temp)
            if temp ==None:
                pass
            elif temp == b"on":
               p2.value(1)
            elif temp == b'off':
               p2.value(0) 
            else:
                skt.send(temp+" from esp32")
                p38.value(0)
                time.sleep_ms(200)
                p38.value(1)
            time.sleep_ms(500)
        
        
        
        
        
